/***************************************************************************
 * 文件名：EnvironmentVariableUtil
 * 功能：
 * 说明：
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/10 19:17:40
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using Microsoft.Win32;
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace BuiltInTools
{
	public class EnvironmentVariableUtil
	{
		/// <summary>
		/// 添加系统环境变量
		/// </summary>
		/// <param name="variableName"></param>
		/// <param name="variableValue"></param>
		/// <exception cref="Exception"></exception>
		public static void GeneratorEnvironmentVariable(string variableName, string variableValue)
		{
			try
			{
				using (RegistryKey envKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
				{
					envKey.SetValue(variableName, variableValue, RegistryValueKind.ExpandString);
				}
			}
			catch (Exception ex)
			{
				throw new Exception($" 系统变量 {variableName}-{variableValue} 创建失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 检测是否存在系统变量
		/// </summary>
		/// <param name="variableName"></param>
		/// <returns></returns>
		public static bool CheckExistEnvironmentVariable(string variableName)
		{
			string envirorment = Environment.GetEnvironmentVariable(variableName);
			return !string.IsNullOrEmpty(envirorment);
		}

		/// <summary>
		/// 获取环境变量值
		/// </summary>
		/// <param name="variableName"></param>
		/// <returns></returns>
		public static string GetEnvironmentVariable(string variableName)
		{
			string envirorment = Environment.GetEnvironmentVariable(variableName);
			return envirorment;
		}

		/// <summary>
		/// 是否管理员权限运行
		/// </summary>
		/// <returns></returns>
		public static bool IsAdministrator()
		{
			return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
		}

		/// <summary>
		/// 消息通知
		/// </summary>
		public static void Notice()
		{
			// 发送简单弹窗
			Win32Notify.MessageBox(IntPtr.Zero, "环境变量添加成功!", "通知", 0x40); // 0x40=信息图标
		}
	}

	/// <summary>
	/// 定义 Windows API
	/// </summary>
	public class Win32Notify
	{
		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		public static extern int MessageBox(IntPtr hWnd, string text, string caption, int type);
	}

}
